package com.huawei.fakedouyin.http


import com.huawei.fakedouyin.util.logDebug
import com.huawei.fakedouyin.util.printJson
import okhttp3.Interceptor
import okhttp3.Request
import okhttp3.Response
import okio.Buffer
import java.nio.charset.Charset


/**
 * 网络请求添加日志
 */
class LogPrintInterceptor : Interceptor {
    override fun intercept(chain: Interceptor.Chain): Response {
        var original:Request = chain.request()
        var response = chain.proceed(original)
        logDebug(
            String.format(
                "请求链接：%s\n请求头：%s\n请求参数：%s\n请求响应：%s",
                original.url(),
                original.headers(),
                printJson(getRequestInfo(original)),
                printJson(getResponseInfo(response))
            )
        )
        return response
    }

    /**
     * 获取请求信息
     */
    private fun getRequestInfo(request: Request): String {
        var str = ""
        val requestBody = request.body()
        val path = request.url().uri().path
        if (path.contains("upload/upload") || path.contains("event/add")) return "文件上传，请求不做打印"
        try {
            val bufferedSink = Buffer()
            requestBody?.writeTo(bufferedSink)
            val charset = Charset.forName("utf-8")
            str = bufferedSink.readString(charset)
        } catch (e: Exception) {
        }
        return str
    }

    /**
     * 获取响应信息
     */
    private fun getResponseInfo(response: Response): String {
        var str = ""
        val responseBody = response.body()
        if (response.request().method() == "GET") return "非正常响应，不做打印"
        try {
            val contentLength = responseBody?.contentLength()
            val source = responseBody?.source()
            source?.request(Long.MAX_VALUE)
            val buffer = source?.buffer
            val charset = Charset.forName("utf-8")
            if (contentLength != 0L) {
                str = buffer?.clone()?.readString(charset) ?: ""
            }
        } catch (e: Exception) {
        }
        return str
    }

}